package agent.teekonna.behaviour;

import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;
import jade.util.Logger;

import java.util.logging.Level;

import agent.keskkonna.KeskkonnaAgent;
import agent.params.LocationParam;
import agent.params.SpeedParam;
import agent.teavitus.TeavitusAgent;
import agent.teekonna.TeekonnaAgent;
import agent.util.AgentUtil;

public class TeekonnaBehaviour extends CyclicBehaviour {

	private static final long serialVersionUID = 1L;
	private static final Logger LOG = Logger
			.getJADELogger(TeekonnaBehaviour.class.getName());

    public TeekonnaBehaviour(TeekonnaAgent myAgent) {
        super(myAgent);
    }
    
	@Override
	public void action() {
		ACLMessage msg = myAgent.receive();
		if (msg == null) {
			block();
		} else {
			// sõnum tuli Keskkonna Agendilt
			if(msg.getSender().equals(AgentUtil.createLocalAid(KeskkonnaAgent.class))){
				analyzeData(msg);
			}
			// sõnum tuli Teavituste agendilt
			if(msg.getSender().equals(AgentUtil.createLocalAid(TeavitusAgent.class))){
				receiveTeavitusMessage(msg);
			}
		}
	}

	private void receiveTeavitusMessage(ACLMessage msg) {
		String info=msg.getContent();
		String gpsE=msg.getUserDefinedParameter(LocationParam.LOCATION_GPS_E.toString());
		String gpsN=msg.getUserDefinedParameter(LocationParam.LOCATION_GPS_N.toString());
		LOG.log(Level.INFO,"Received message from Teavituse agent with message "+info+" at "+gpsE+" "+gpsN);
	}

	private void analyzeData(ACLMessage msg) {
		String queryId=msg.getReplyWith();
		String avgSpeed =msg.getUserDefinedParameter(SpeedParam.AVG_SPEED.toString());		
		String toGpsE=msg.getUserDefinedParameter(LocationParam.LOCATION_GPS_E.toString());
		String toGpsN=msg.getUserDefinedParameter(LocationParam.LOCATION_GPS_N.toString());
		String fromGpsE=msg.getUserDefinedParameter(LocationParam.LOCATION_FROM_GPS_E.toString());
		String fromGpsN=msg.getUserDefinedParameter(LocationParam.LOCATION_FROM_GPS_N.toString());
		
		LOG.log(Level.INFO,"The average speed on route from "+toGpsE+" "+toGpsN+" to "+fromGpsE+" "+fromGpsN+" is "+avgSpeed+". Query ID "+queryId);
		
	}

}
